<template>
  <div :id="chartId" class="chart-box" />
</template>

<script>
import echarts from "echarts";
import resize from "./mixins/resize";
export default {
  mixins: [resize],
  props: {
    chartTitle: {
      type: String,
      default: "title",
    },
    chartId: {
      type: String,
      default: "chart",
    },
    barList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    barList: {
      handler(val) {
        this.$nextTick(() => {
          this.initChart(val);
        });
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    initChart(data) {
      const xData = [];
      const yData = [];
      if (data && data.length > 0) {
        data.forEach((el) => {
          const label = el.label ? el.label : " ";
          const rate = el.scoreRate ? el.scoreRate : el.countRate;
          xData.push(label);
          yData.push(rate);
        });
      }
      this.chart = echarts.init(document.getElementById(this.chartId));
      const option = {
        color: "#7874FF",
        title: {
          text: this.chartTitle,
          subtext: '',
          left: 'center'
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            let str=params[0].name
            params.forEach((item,index)=>{
              str=str+'<br/>'+ '<div style="height: 10px;width: 10px;display:inline-block;margin-right:5px;border-radius: 50%;background:'+params[index].color+'"></div>' + (item.value*100).toFixed(2)+'%'
            })
            return str
          }
        },
        grid: {
          top: "20px",
        },
        xAxis: {
          type: "category",
          data: xData,
          axisLabel: {
            color: "#69A3F3",
            interval: 0,
            //rotate: -40,
          },
          splitLine: {
            lineStyle: {
              color: ["#305296"],
              width: 1,
              type: "solid",
            },
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#69A3F3",
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ["#305296"],
              width: 1,
              type: "solid",
            },
          },
        },
        series: [
          {
            data: yData,
            barMaxWidth: 30,
            type: "bar",
          },
        ],
      };
      this.chart.setOption(option);
    },
  },
};
</script>

<style lang="scss" scoped>
.chart-box {
  width: 100%;
  min-height: 200px;
}
</style>
